package LeetCode.month03.day81;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author 16778
 * @date 2025/10/21 8:06
 * @description
 */
public class No3346 {
    //差分
    public int maxFrequency(int[] nums, int k, int numOperations) {
        Map<Integer,Integer> cnt = new HashMap<>();
        Map<Integer,Integer> diff = new TreeMap<>();
        for (int num : nums) {
            cnt.merge(num,1,Integer::sum);
            diff.putIfAbsent(num,0);
            diff.merge(num-k,1,Integer::sum);
            diff.merge(num+k+1,-1,Integer::sum);
        }

        int sum = 0;
        int res = 0;
        for (Map.Entry<Integer, Integer> entry : diff.entrySet()) {
            sum+=entry.getValue();
            res = Math.max(res,Math.min(sum,cnt.getOrDefault(entry.getKey(),0)+numOperations));
        }
        return res;
    }
}
